//
//  YJTrainVideoPlayer.swift
//  yuejian
//
//  Created by 闫子夜 on 2017/10/25.
//  Copyright © 2017年 gyy. All rights reserved.
//

import UIKit
import AVFoundation

class VideoPlayer: UIView {
    private var playerItem:AVPlayerItem!
    private var player:AVPlayer!
    private var menuView:UIView!
    private var timeLabel:UILabel!
    private var slider:UISlider!
    private var obser:Any!
    private var sliding:Bool = true
    
    var fullBtn:UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    func initialize(itemUrl:String){
        backgroundColor = .black
        clipsToBounds = true
        
        let url = URL(string: itemUrl)
        playerItem = AVPlayerItem(url: url!)
        player = AVPlayer(playerItem: playerItem)
        
        let playerLayer = AVPlayerLayer()
        playerLayer.player = player
        playerLayer.frame = bounds
        playerLayer.videoGravity = AVLayerVideoGravity(string: AVVideoScalingModeResizeAspect) as String
        layer.addSublayer(playerLayer)
        
        menuView = UIView(frame: CGRect(x: 0, y: bounds.height-35, width: bounds.width, height: 35))
        menuView.backgroundColor = .clear
        let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.dark))
        blurEffectView.frame = menuView.bounds
        blurEffectView.alpha = 0.4
        menuView.addSubview(blurEffectView)
        addSubview(menuView)
        
        let playBtn = UIButton(frame: CGRect(x: 10, y: 5, width: 25, height: 25))
        playBtn.setImage(UIImage(named:"play.png")?.scaleImageToSize(playBtn.bounds.size), for: .normal)
        playBtn.tintColor = UIColor.white
        playBtn.addTarget(self, action: #selector(play), for: .touchUpInside)
        menuView.addSubview(playBtn)
        
        fullBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
        fullBtn.center = CGPoint(x: bounds.width-35+25/2, y: playBtn.center.y)
        fullBtn.setImage(UIImage(named:"full.png"), for: .normal)
        fullBtn.tintColor = UIColor.white
        menuView.addSubview(fullBtn)
        
        slider = UISlider(frame: CGRect(x: 0, y: 0, width: bounds.width-140, height: 5))
        slider.center = CGPoint(x: 40+bounds.width/2-70, y: playBtn.center.y)
        slider.backgroundColor = .white
        slider.maximumValue = 1
        slider.minimumValue = 0
        slider.value = 0
        let thumbImg = UIImage(named: "thumb.png")?.scaleImageToSize(CGSize(width: 10, height: 10))
        slider.setThumbImage(thumbImg, for: .normal)
        slider.addTarget(self, action: #selector(slidertouchDown), for: .touchDown )
        slider.addTarget(self, action: #selector(slidertouchOut), for: .touchUpInside)
        menuView.addSubview(slider)
        
        timeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 65, height: 20))
        timeLabel.center = CGPoint(x: bounds.width-64, y: playBtn.center.y)
        timeLabel.text = "00:00/00:00"
        timeLabel.font = UIFont.systemFont(ofSize: 10)
        timeLabel.backgroundColor = UIColor.clear
        timeLabel.textColor = UIColor.white
        menuView.addSubview(timeLabel)
        
        addObser()
        
        perform(#selector(self.hideMenuView), with: self, afterDelay: 3)
    }
    
    @objc private func play(sender:UIButton){
        if player.rate == 0{
            player.play()
            sender.setImage(UIImage(named:"pause.png"), for: .normal)
        }
        else if player.rate == 1{
            player.pause()
            sender.setImage(UIImage(named:"play.png"), for: .normal)
        }
    }
    
    @objc private func addObser(){
        obser = player.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 1), queue: .main) { [weak self](time) in
            var totalSec:String!
            var currentSec:String!
            let currentTime = CMTimeGetSeconds(time)
            let totalTime = CMTimeGetSeconds(self!.playerItem.duration)
            if self!.sliding{
                self!.slider.setValue(Float(currentTime/totalTime), animated: true)
            }
            if currentTime.isNaN || totalTime.isNaN{
                totalSec = "00:00"
                currentSec = "00:00"
            }else{
                totalSec = String(format: "%02d:%02d", Int(totalTime/60),Int(totalTime.truncatingRemainder(dividingBy: 60)))
                currentSec = String(format: "%02d:%02d", Int(currentTime/60),Int(currentTime.truncatingRemainder(dividingBy: 60)))
            }
            self?.timeLabel.text = "\(currentSec!)/\(totalSec!)"
        }
    }
    
    private func showMenuView(){
        if menuView.frame.origin.y == bounds.height{
            UIView.animate(withDuration: 0.2, animations: {
                self.menuView.frame.origin.y = self.bounds.height - self.menuView.bounds.height
            }, completion: { (_) in
                self.perform(#selector(self.hideMenuView), with: self, afterDelay: 3)
            })
        }
    }
    
    @objc func hideMenuView(){
        let animation = CABasicAnimation(keyPath: "position.y")
        animation.duration = 0.2
        self.menuView.layer.frame.origin.y = bounds.height
        self.menuView.layer.add(animation, forKey: nil)
    }
    
    @objc private func slidertouchDown(){
        sliding = !sliding
    }
    
    @objc private func slidertouchOut(){
        player.seek(to: CMTime(seconds: Double(slider.value*Float(CMTimeGetSeconds(playerItem.duration))), preferredTimescale:  1)) { [weak self](_) in
            self!.sliding = !(self!.sliding)
        }
    }
    
    func disAppear(){
        player.removeTimeObserver(obser)
        obser = nil
        player = nil
        removeFromSuperview()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        showMenuView()
    }
    
    deinit {
        print("deinit")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

